package cn.wizzer.app.task.commons.ext.quartz.job;

import cn.wizzer.app.crown.modules.models.CrownConfig;
import cn.wizzer.app.crown.modules.services.CrownConfigService;
import cn.wizzer.app.crown.modules.services.pl.bk.BKRResolverService;
import cn.wizzer.app.crown.modules.services.pl.ft.*;
import cn.wizzer.framework.util.ThreadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 获取独赢单式任务
 */
@IocBean
public class CrownJobMatchR implements Job {

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private RResolverService ftR;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private BKRResolverService bkR;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private CrownConfigService crownConfigService;

    private static final Log log = Logs.get();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取一个爬虫账号 线程安全
        CrownConfig crownConfig = crownConfigService.syncOne("获取独赢单式任务");
        if (null != crownConfig) {
            log.info("准备开始任务:" + crownConfig);
            ThreadUtil.execute(new Runnable() {
                @Override
                public void run() {
                    crawler(crownConfig, jobExecutionContext);
                }
            });
        }
    }

    private void crawler(CrownConfig crownConfig, JobExecutionContext jobExecutionContext) {
        try {
            // 足球独赢&&让球&&大小
            ftR.browse(crownConfig);
            ftR.future(crownConfig);
            // 篮球独赢&&让球&&大小
            bkR.browse(crownConfig);
            bkR.future(crownConfig);
        } catch (Exception e) {
            log.error("单式定时任务异常" + e.getMessage());
        } finally {
            // 获取账号，判断是否为空，以防账号已经被清除
            crownConfigService.release(crownConfig);
        }
    }
}
